package cn.yunhe.java.service;

import cn.yunhe.java.object.MenuInfo;
import cn.yunhe.java.dao.SysMenuMapper;
import cn.yunhe.java.dao.SysUserMapper;
import cn.yunhe.java.pojo.SysMenu;
import cn.yunhe.java.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SysUserMapper dao;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public SysUser findByLoginName(String username) {
        return dao.findByeLoginName(username);
    }

    /**
     * 查询菜单信息
     * @return
     */
    @Override
    public Map<String, Object> queryMenu(Integer userId) {

        Map<String,Object> rtnMap = new HashMap<>();
        //首页
        Map<String,String> homeInfoMap = new HashMap<>();
        homeInfoMap.put("title","首页");
        homeInfoMap.put("href","login/home");
        rtnMap.put("homeInfo",homeInfoMap);
        //logo
        Map<String,String> logoInfoMap = new HashMap<>();
        logoInfoMap.put("title","云和学院");
        logoInfoMap.put("image","statics/images/logo.png");
        logoInfoMap.put("href","http://www.baidu.com");
        rtnMap.put("logoInfo",logoInfoMap);

        //菜单信息
        rtnMap.put("menuInfo",menuInfos(userId,0));
        return rtnMap;
    }

    //利用递归查询菜单信息
    private List<MenuInfo> menuInfos(Integer userId,Integer pMenuId){
        List<SysMenu> levelList = sysMenuMapper.selectByPMenuId(userId,pMenuId);

        List<MenuInfo> rtnList = new ArrayList<>();

        for(SysMenu sysMenu : levelList){
           MenuInfo menuInfo = new MenuInfo();
           menuInfo.setTitle(sysMenu.getTitle());
           menuInfo.setHref(sysMenu.getHref());
           menuInfo.setIcon(sysMenu.getIcon());
           menuInfo.setTarget(sysMenu.getTarget());
           //先查询当前菜单是否有子菜单
            if(sysMenu.getChildTotal()>0)
              menuInfo.setChild(menuInfos(userId,sysMenu.getMenuId()));
            rtnList.add(menuInfo);
        }
        return rtnList;
    }

    @Override
    public int updatePassword(Integer id, String sha256) {
        return dao.updatePassword(id,sha256);
    }
}
